//
//  ZXHomeCollectionViewController.swift
//  loveBee
//
//  Created by zhangxing on 2017/8/12.
//  Copyright © 2017年 zhangXing. All rights reserved.
//

import UIKit



class ZXHomeCollectionViewController: UICollectionViewController {
    
    //实例化一个ZXHomeViewModel类型的viewModel对象
    var homeViewModel: ZXHomeViewModel = ZXHomeViewModel()
    
    //懒加载左边的扫一扫item
    lazy var scanItem: UIBarButtonItem = {

        //创建自定义的view
        let contentView = UIView.init(frame: CGRect(x: 0, y: 0, width: 55, height: 60))

        //创建button(接下来需要自定义button)
        //我们想要调整button的位置,就设置x值就可以了
        let btn = ZXButton.init(frame: CGRect(x: -15, y: 0, width: contentView.width!, height: contentView.height!))
        
        //设置button的图片
        btn.setImage(#imageLiteral(resourceName: "icon_black_scancode"), for: .normal)
        
        //设置btn的文字
        btn.setTitle("扫一扫", for: .normal)
        
        //设置btn的文字大小
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        
        //设置btn文字居中
        btn.titleLabel?.textAlignment = .center
        
        //设置btn的文字颜色
        btn.setTitleColor(UIColor.black, for: .normal)
        
        //添加事件
        btn.addTarget(self, action: #selector(clickScanItem(btn:)), for: .touchUpInside)

        //将btn添加到contentView中
        contentView.addSubview(btn)
        
        //设置UIBarButtonItem的自定义视图为contentView
        let scanItem = UIBarButtonItem.init(customView: contentView)
        
        
        
        return scanItem
        
    }()
    
    
    
    //懒加载导航栏右侧的searchItem
    lazy var searchItem: UIBarButtonItem = {
        
        let contentView = UIView.init(frame: CGRect(x: 0, y: 0, width: 55, height: 60))
        
        //创建自定义的button
        let btn = ZXButton.init(frame: CGRect(x: 0, y: 0, width: contentView.width!, height: contentView.height!))
        
        btn.setImage(#imageLiteral(resourceName: "icon_search"), for: .normal)
        
        btn.setTitle("搜索", for: .normal)
        
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 12)

        btn.titleLabel?.textAlignment = .center
        
        btn.setTitleColor(UIColor.black, for: .normal)
        
        //添加事件
        btn.addTarget(self, action: #selector(clickSearchItem), for: .touchUpInside)
        
        contentView.addSubview(btn)
        
        let searchItem = UIBarButtonItem.init(customView: contentView)
        
        return searchItem
    
    }()
    //懒加载rightSpacer,当我们在调整UIBarButtonItem的位置的时候,可以让x点的值改变,当然也可以使用rightBarButtonItems设置rightSpacer
    lazy var rightSpacer: UIBarButtonItem = {
        
        //设置导航栏的rightBarButttonItem的间隙spacer
        let rightSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        
        rightSpacer.width = -15
        
        return rightSpacer
        
    }()
    
    
    
    //懒加载导航栏的titleView
    //  MARK: --   懒加载
    private lazy var titleLabel: UILabel = {
        
        //实例化一个label
        let label = UILabel(fontSize: 17, textColor: UIColor.darkGray)
        
        label.layer.borderColor = UIColor.gray.cgColor
        
        label.layer.borderWidth = 1
        
        //灰色阴影
//        label.shadowColor = UIColor.blue
        //阴影的偏移量
//        label.shadowOffset = CGSize(width: 1, height: 1)
        
        //设置label可与用户交互
        label.isUserInteractionEnabled = true
        
        //设置点击手势
        let tap = UITapGestureRecognizer(target: self, action: #selector(clickTitleLabel))
        
        //给label添加点击手势
        label.addGestureRecognizer(tap)
        
        //name1
        let name1 = "配送至 :"
        
        //name2
        let name2 = " 宏仕发商务楼  "
        
        //拼接title
        let title = name1 + name2
        
        //把字符串转成富文本
        let attributedStr: NSMutableAttributedString = NSMutableAttributedString(string: title)
        
        //获取name1名字的范围
        let name1Range = (title as NSString).range(of: name1)
        
        //获取name2名字的范围
        let name2Range = (title as NSString).range(of: name2)
        
        //给指定name1Range范围添加对应的富文本属性
        attributedStr.addAttributes([NSForegroundColorAttributeName: UIColor.brown, NSFontAttributeName: UIFont.systemFont(ofSize: 12)], range: name1Range)
        
        //给指定name2Range范围添加对应的富文本属性
        attributedStr.addAttributes([NSForegroundColorAttributeName: UIColor.brown, NSFontAttributeName: UIFont.systemFont(ofSize: 17)], range: name2Range)
        
        //1.创建图片对象
        var image = UIImage(named: "allowBlack")
        
        //1.1   给定重置图片的大小
        let reSize = CGSize(width: 14, height: 10)
        
        //1.2   重新设置图片的大小
//         image = image?.reSizeImage(reSize: reSize)
        image = image?.scaleImage(scaleSize: 0.7)
        //2.创建文本附件
        let textAttachment = NSTextAttachment()
        
        //3.设置文本附件所需要的图片
        textAttachment.image = image
        
        //4.根据文本附件创建富文本
        let attributedString = NSAttributedString(attachment: textAttachment)
        
        //5.拼接富文本
        attributedStr.append(attributedString)
        
        //设置label的富文本属性attributedText
        label.attributedText = attributedStr
        
        
        //设置居中
        label.textAlignment = .center
        
        //自适应大小
        label.sizeToFit()
        
        return label
    }()
    
    
    
    //懒加载下拉刷新视图
    lazy var downPullRefreshView: ZXRefreshControl = {
        
        //初始化一个下拉控件downPullRefreshView
        let downPullRefreshView = ZXRefreshControl()
        
        //添加下拉控件的监听值改变事件
        downPullRefreshView.addTarget(self, action: #selector(downPullRefreshAction), for: .valueChanged)
        
        
        return downPullRefreshView
        
        
    }()
    
    
    //上拉刷新视图,我们使用了自定义的视图,千万别忘了注册自定义的组尾视图,如果不注册,你自定义的视图永远也不会执行,那么upPullView也就永远为nil,那么upPullView!强制解包也就永远报错
    var upPullView: ZXFooterCollectionReusableView?

    
    //  MARK: --   flowLayout初始化方法
    override init(collectionViewLayout layout: UICollectionViewLayout) {
        //创建flowLayout
        super.init(collectionViewLayout: layout)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        //设置collectionview的背景色
        self.collectionView?.backgroundColor = UIColor.init(hex: 0xEFEFEF)
        
        //homeViewModel.loadCellData这句一定要放在viewDidLoad中,这样视图一要显示,就会去加载网络数据
        homeViewModel.loadCellData { [unowned self] (isSucceed) in
            if isSucceed {
                //如果加载数据成功,就让collectionView刷新数据
                self.collectionView?.reloadData()
            }
            else {
                
                print("数据加载失败")
            }
        }

       
        setupUI()

       
    }
    
    
    private func setupUI() {
        
        //添加下拉刷新控件
        setupRefreshView()
        
        //搭建导航栏
        setupNav()
        
        //设置collectionview属性
        setCollectionViewNature()
        
        
        
    }
    
    
    //  MARK: --   添加下拉刷新控件
    private func setupRefreshView() {
        
        collectionView?.addSubview(downPullRefreshView)
    }

    
    
    //  MARK: --   搭建nav
    private func setupNav() {
        //设置导航栏的leftBarButtonItem
        navigationItem.leftBarButtonItem = scanItem
        
        //设置导航栏的rightBarButtonItem
        navigationItem.rightBarButtonItems = [rightSpacer, searchItem]
        
        //设置导航栏的titleView
        navigationItem.titleView = titleLabel
        
        //修改导航栏按钮颜色(没实现)
//        navigationController?.navigationBar.tintColor = UIColor.init(hex: 0xFFDE00)
        
        //修改导航栏文字颜色(没实现)
        //        self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]

        
        //修改导航栏背景色1(可以)
//        self.navigationController?.navigationBar.barTintColor = UIColor.init(hex: 0xFFDE00)
        
        //设置导航栏的背景图片2(可以)
        navigationController?.navigationBar.setBackgroundImage(#imageLiteral(resourceName: "v2_coupon_verify_normal"), for: .default)
        
        
        
      
    }
    
    //  MARK: --   设置collectionview属性
    private func setCollectionViewNature() {
        //设置collectionView的数据源
        collectionView?.dataSource = self
        
        //设置collectionView的代理
        collectionView?.delegate = self
        
        //注册cell
//        collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: IDHomeCell)
        
        //使用xib注册cell
        collectionView?.register(UINib.init(nibName: "ZXHomeCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: IDHomeCell)
        
        //获取布局对象
        let flowLayout = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
        
        //设置组头的高度
        flowLayout.headerReferenceSize = CGSize(width: KWidth, height: 900)
        
        //设置组尾的高度(这是用来做下拉刷新的)
        flowLayout.footerReferenceSize = CGSize(width: KWidth, height: 50)
        
        
        //计算cell的宽度(因为collectionview的两边都有一个distance,两个cell之间也有一个distance)
        let cellW = (KWidth - 3 * homeDistance) * 0.5
        
        //计算cell的高度
        let cellH = cellW + 70
        
        //设置itemSize
        flowLayout.itemSize = CGSize(width: cellW, height: cellH)
        
        //设置cell的内边距(你得保证每一个cell的两边都有一个homeDistance,因为你在前面计算cell的宽度和高度的时候就是根据cell的左右两边都有一个distance,两个cell之间有一个distance来计算的,如果你这个内边距不设置,cell就会靠在左右两边,不明白上下设置都没有用)
        flowLayout.sectionInset = UIEdgeInsetsMake(0, homeDistance, 0, homeDistance)
        
        
        //注册组头( 在注册cell 的同时，别忘了注册header使用自定义的视图ZXHeaderCollectionReusableView)
        collectionView?.register(ZXHeaderCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: IDGroupHeader)
        
        //注册组尾( 在注册cell 的同时，别忘了注册footer要使用自定义的ZXFooterCollectionReusableView这个类型,否则一直报upPullView!强制解包的错误)
        collectionView?.register(ZXFooterCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: IDGroupFooter)
        
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

   
    // MARK: 设置UICollectionViewDataSource的数据源方法
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        return 1
    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return homeViewModel.homeCellViewModelList.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: IDHomeCell, for: indexPath) as! ZXHomeCollectionViewCell
    //设置cell随机色

        cell.backgroundColor = UIColor.white
        
        //传递数据
        cell.homeCellViewModel = homeViewModel.homeCellViewModelList[indexPath.item
        ]
    
        return cell
    }
    
    
    
    //返回组头组尾视图
    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        //如果是组头
        if kind == UICollectionElementKindSectionHeader {
            
            //获取组头 // youbiandong
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: IDGroupHeader, for: indexPath)
            
            headerView.backgroundColor = UIColor.init(hex: 0xEFEFEF)
            
            return headerView
        }
        else {
            
            //获取组尾(因为本身footerView就是UICollectionReusableView类型的,我们在前面懒加载一个UICollectionReusableView类型的视图upPullView来接收UICollectionReusableView类型的值,没有问题,接下来我们就要自定义UICollectionReusableView视图,我们需要自定义一个视图继承自UICollectionReusableView类型)
            
            upPullView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: IDGroupFooter, for: indexPath) as? ZXFooterCollectionReusableView
            
            
            upPullView?.backgroundColor = RandomColor()
            
            return upPullView!
            //当我们还没有对自定义的ZXFooterCollectionReusableView做任何操作,会报强制解包错误fatal error: unexpectedly found nil while unwrapping an Optional value(为什么定义了后还是报强制解包的错,因为我们在注册的时候还是使用了系统的//注册组尾( 在注册cell 的同时，别忘了注册footer)
//            collectionView?.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: IDGroupFooter),我们应该使用ZXFooterCollectionReusableView.self)
            
        }
    }
    
    
    
    
    
    

    //  MARK: --   点击扫一扫按钮执行的方法
    @objc private func clickScanItem(btn: UIButton) {
        
        print("点击了首页的扫一扫")
        
        
        
    }
    
    @objc private func clickSearchItem() {
        
        print("点击了首页的搜索按钮")
    }
    
    @objc private func clickTitleLabel() {
        
        print("点击了导航栏的titleView")
    }
    
    
    //  MARK: --   监听下拉刷新的时间
    @objc private func downPullRefreshAction() {
        
        
//        print("//延迟5秒结束刷新动画")
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5) { 
            self.downPullRefreshView.endRefreshing()
        }
        
        
    }
    
}
